package main

import (
	"net"
	"os"

	log "github.com/kpango/glg"
	crono "github.com/utahta/go-cronowriter"
	"google.golang.org/grpc"
	"gopkg.in/alecthomas/kingpin.v2"

	"../pb"
)

var (
	BufSize    = kingpin.Flag("buffer", "buffer size.").Short('b').Default("1048576").Int()
	Logger     = kingpin.Flag("log", "log file").Short('l').Default("RfdService-server.log").String()
	Port       = kingpin.Flag("port", "listen port").Short('p').Default("10101").String()
	ResendNum  = kingpin.Flag("resend", "how many times to resend if failed").Short('n').Default("5").Int()
	AdminPort  = kingpin.Flag("admin", "admin api port").Short('a').Default("10102").String()
	RuleFile   = kingpin.Flag("rule", "rule file").Short('r').Default("rules.yml").String()
	PasswdFile = kingpin.Flag("passwd", "password file").Default("auth.enc").String()
)

func main() {
	kingpin.Parse()
	logger := crono.MustNew(*Logger+".%Y%m%d", crono.WithInit())
	log.Get().SetMode(log.WRITER).AddWriter(logger).AddWriter(os.Stdout)

	admin, err := NewAdmin()
	defer admin.Close()
	if err != nil {
		log.Errorf("failed to new admin: %v", err)
		os.Exit(1)
	}
	go Serve(":"+*AdminPort, admin)

	listener, err := net.Listen("tcp", ":"+*Port)
	if err != nil {
		log.Errorf("failed to listen: %v", err)
		os.Exit(1)
	}
	defer listener.Close()

	gs := grpc.NewServer()
	pb.RegisterRfdServiceServer(gs, &RfdService{bufferSize: *BufSize, resendNum: *ResendNum})
	gs.Serve(listener)
}
